<template>
  <view class="order-detail-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">订单详情</text>
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 订单详情内容 -->
    <view class="detail-content" v-else-if="orderDetail">
      <!-- 订单状态卡片 -->
      <view class="status-card">
        <view class="status-icon">
          <text class="icon-text">{{ getStatusIcon(orderDetail.status) }}</text>
        </view>
        <view class="status-info">
          <text class="status-text">{{ orderDetail.statusText }}</text>
          <text class="status-desc" v-if="getStatusDesc(orderDetail.status)">
            {{ getStatusDesc(orderDetail.status) }}
          </text>
        </view>
      </view>
      
      <!-- 配送信息 -->
      <view class="section">
        <view class="section-title">配送信息</view>
        <view class="info-item">
          <text class="info-label">收货人</text>
          <text class="info-value">{{ orderDetail.deliveryName }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">联系电话</text>
          <text class="info-value">{{ orderDetail.deliveryPhone }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">收货地址</text>
          <text class="info-value">{{ orderDetail.deliveryAddress }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.scheduledDeliveryDate">
          <text class="info-label">配送时间</text>
          <text class="info-value">
            {{ orderDetail.scheduledDeliveryDate }} {{ orderDetail.scheduledDeliveryTime }}
          </text>
        </view>
      </view>
      
      <!-- 商家信息 -->
      <view class="section">
        <view class="section-title">商家信息</view>
        <view class="merchant-info">
          <text class="merchant-name">{{ orderDetail.merchantName }}</text>
        </view>
      </view>
      
      <!-- 商品列表 -->
      <view class="section">
        <view class="section-title">商品信息</view>
        <view class="goods-list">
          <view 
            class="goods-item" 
            v-for="(item, index) in orderDetail.items" 
            :key="index"
          >
            <image 
              :src="item.foodImage || '/static/food1.jpg'" 
              mode="aspectFill"
              class="goods-image"
            />
            <view class="goods-info">
              <text class="goods-name">{{ item.foodName }}</text>
              <text class="goods-spec" v-if="item.spiceLevel">{{ item.spiceLevel }}</text>
              <view class="goods-price-row">
                <text class="goods-price">¥{{ item.foodPrice }}</text>
                <text class="goods-quantity">x{{ item.quantity }}</text>
              </view>
            </view>
            <text class="goods-subtotal">¥{{ item.subtotal }}</text>
          </view>
        </view>
      </view>
      
      <!-- 订单信息 -->
      <view class="section">
        <view class="section-title">订单信息</view>
        <view class="info-item">
          <text class="info-label">订单编号</text>
          <text class="info-value">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">下单时间</text>
          <text class="info-value">{{ formatTime(orderDetail.createdAt) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.paidAt">
          <text class="info-label">支付时间</text>
          <text class="info-value">{{ formatTime(orderDetail.paidAt) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.notes">
          <text class="info-label">备注</text>
          <text class="info-value">{{ orderDetail.notes }}</text>
        </view>
      </view>
      
      <!-- 费用明细 -->
      <view class="section">
        <view class="section-title">费用明细</view>
        <view class="price-item">
          <text class="price-label">商品金额</text>
          <text class="price-value">¥{{ orderDetail.foodAmount }}</text>
        </view>
        <view class="price-item">
          <text class="price-label">配送费</text>
          <text class="price-value">¥{{ orderDetail.deliveryFee }}</text>
        </view>
        <view class="price-item total">
          <text class="price-label">实付金额</text>
          <text class="price-value highlight">¥{{ orderDetail.totalAmount }}</text>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-container" v-else>
      <text class="empty-text">订单不存在</text>
    </view>
    
    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="orderDetail && shouldShowActions()">
      <!-- 待支付 -->
      <template v-if="orderDetail.status === 'pending'">
        <button class="action-btn outline" @click="cancelOrder">取消订单</button>
        <button class="action-btn primary" @click="payOrder">立即支付</button>
      </template>
      
      <!-- 已支付/备货中 -->
      <template v-if="['paid', 'preparing'].includes(orderDetail.status)">
        <button class="action-btn outline" @click="cancelOrder">取消订单</button>
        <button class="action-btn danger" @click="refundOrder">申请退款</button>
      </template>
      
      <!-- 配送中 -->
      <template v-if="orderDetail.status === 'shipping'">
        <button class="action-btn danger" @click="refundOrder">申请退款</button>
        <button class="action-btn primary" @click="confirmDelivery">确认收货</button>
      </template>
      
      <!-- 已完成 -->
      <template v-if="orderDetail.status === 'delivered'">
        <button 
          v-if="!orderDetail.isReviewed" 
          class="action-btn primary" 
          @click="goToReview"
        >
          去评价
        </button>
        <button 
          v-else 
          class="action-btn outline" 
          @click="viewReview"
        >
          查看评价
        </button>
      </template>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import orderService from '../../services/order.js'
import { backToOrders } from '../../utils/navigation.js'
import CustomModal from '../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      loading: false,
      orderId: null,
      orderDetail: null
    }
  },
  
  onLoad(options) {
    this.getStatusBarHeight()
    
    if (options.id) {
      this.orderId = options.id
      this.loadOrderDetail()
    } else {
      uni.showToast({
        title: '订单ID缺失',
        icon: 'error'
      })
    }
  },
  
  methods: {
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      // 设置 CSS 变量，用于固定导航栏定位
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },
    
    goBack() {
      backToOrders()
    },
    
    // 加载订单详情
    async loadOrderDetail() {
      if (!this.orderId || this.loading) return
      
      this.loading = true
      
      try {
        console.log('加载订单详情 - 订单ID:', this.orderId)
        
        const response = await orderService.getOrderDetail(this.orderId)
        console.log('订单详情响应:', response)
        
        if (response && response.data) {
          this.orderDetail = orderService.formatOrderDetail(response.data)
          console.log('订单详情加载成功:', this.orderDetail)
        }
        
      } catch (error) {
        console.error('加载订单详情失败:', error)
        
        let errorMsg = '加载订单详情失败'
        if (error.message && error.message.includes('404')) {
          errorMsg = '订单不存在'
        } else if (error.message && error.message.includes('401')) {
          errorMsg = '请先登录'
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
        
        setTimeout(() => {
          backToOrders()
        }, 2000)
        
      } finally {
        this.loading = false
      }
    },
    
    // 获取状态图标
    getStatusIcon(status) {
      const icons = {
        pending: '⏳',
        paid: '✓',
        preparing: '📦',
        shipping: '🚚',
        delivered: '✓',
        cancelled: '✕',
        refunded: '↩'
      }
      return icons[status] || '•'
    },
    
    // 获取状态描述
    getStatusDesc(status) {
      const descs = {
        pending: '请尽快完成支付',
        paid: '商家正在准备您的订单',
        preparing: '商品正在打包中',
        shipping: '订单正在配送中',
        delivered: '订单已完成',
        cancelled: '订单已取消',
        refunded: '订单已退款'
      }
      return descs[status] || ''
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 是否显示操作按钮
    shouldShowActions() {
      // 已取消、已退款的订单不显示操作按钮
      // 已完成的订单显示评价按钮
      return !['cancelled', 'refunded'].includes(this.orderDetail.status)
    },
    
    // 跳转评价页面
    goToReview() {
      uni.navigateTo({
        url: `/pages/order-review/order-review?orderId=${this.orderDetail.id}`
      })
    },
    
    // 查看评价
    viewReview() {
      uni.navigateTo({
        url: `/pages/my-reviews/my-reviews?orderId=${this.orderDetail.id}`
      })
    },
    
    // 支付订单
    async payOrder() {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '确认支付',
        content: `订单金额：¥${this.orderDetail.totalAmount}\n\n是否确认支付？`,
        confirmText: '确认支付',
        cancelText: '取消',
        onConfirm: async () => {
          try {
            uni.showLoading({
              title: '支付处理中...',
              mask: true
            })
            
            await new Promise(resolve => setTimeout(resolve, 1500))
            await orderService.payOrder(this.orderId, 'mock_payment')
            
            uni.hideLoading()
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            })
            
            setTimeout(() => {
              this.loadOrderDetail()
            }, 1500)
            
          } catch (error) {
            uni.hideLoading()
            console.error('支付失败:', error)
            uni.showToast({
              title: '支付失败',
              icon: 'error'
            })
          }
        }
      })
    },
    
    // 取消订单
    async cancelOrder() {
      this.$refs.customModal.show({
        type: 'warning',
        title: '取消订单',
        content: '确定要取消该订单吗？',
        confirmText: '确定取消',
        cancelText: '再想想',
        onConfirm: async () => {
          try {
            await orderService.cancelOrder(this.orderId, '用户取消')
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            
            setTimeout(() => {
              this.loadOrderDetail()
            }, 1500)
            
          } catch (error) {
            console.error('取消订单失败:', error)
            uni.showToast({
              title: '取消失败',
              icon: 'error'
            })
          }
        }
      })
    },
    
    // 申请退款
    async refundOrder() {
      this.$refs.customModal.show({
        type: 'danger',
        title: '申请退款',
        content: '确认要申请退款吗？',
        confirmText: '确认退款',
        cancelText: '取消',
        showInput: true,
        inputPlaceholder: '请输入退款原因（选填）',
        inputMaxLength: 100,
        onConfirm: async (inputValue) => {
          try {
            const reason = inputValue || '用户申请退款'
            await orderService.refundOrder(this.orderId, reason)
            uni.showToast({
              title: '退款申请已提交',
              icon: 'success'
            })
            
            setTimeout(() => {
              this.loadOrderDetail()
            }, 1500)
            
          } catch (error) {
            console.error('申请退款失败:', error)
            uni.showToast({
              title: '申请失败',
              icon: 'error'
            })
          }
        }
      })
    },
    
    // 确认收货
    async confirmDelivery() {
      // 状态检查：只有配送中的订单才能确认收货
      if (this.orderDetail.status !== 'shipping') {
        uni.showToast({
          title: '当前订单状态无法确认收货',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.$refs.customModal.show({
        type: 'success',
        title: '确认收货',
        content: '确认已收到商品吗？\n\n确认后订单将完成，无法撤销。',
        confirmText: '确认收货',
        cancelText: '再等等',
        onConfirm: async () => {
          try {
            // 调用后端确认收货接口
            await orderService.confirmReceipt(this.orderId)
            
            // 确认成功提示
            uni.showToast({
              title: '确认收货成功',
              icon: 'success',
              duration: 2000
            })
            
            // 延迟后询问是否评价
            setTimeout(() => {
              this.$refs.customModal.show({
                type: 'info',
                title: '给个好评吧',
                content: '您的评价对我们很重要，是否现在去评价？',
                confirmText: '去评价',
                cancelText: '下次再说',
                onConfirm: () => {
                  // 跳转到评价页面
                  uni.navigateTo({
                    url: `/pages/order-review/order-review?orderId=${this.orderId}`
                  })
                },
                onCancel: () => {
                  // 重新加载订单详情
                  this.loadOrderDetail()
                }
              })
            }, 800)
            
          } catch (error) {
            console.error('确认收货失败:', error)
            
            let errorMsg = '确认收货失败'
            if (error.message) {
              if (error.message.includes('404')) {
                errorMsg = '订单不存在'
              } else if (error.message.includes('400')) {
                errorMsg = '订单状态异常，无法确认收货'
              } else if (error.message.includes('401')) {
                errorMsg = '请先登录'
              }
            }
            
            uni.showToast({
              title: errorMsg,
              icon: 'error',
              duration: 2500
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background: #fff;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  z-index: 998;
  
  .nav-left, .nav-right {
    width: 80rpx;
  }
  
  .back-icon {
    font-size: 36rpx;
    color: #333;
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
}

.loading-container, .empty-container {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 200rpx 0;
  
  .loading-text, .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.detail-content {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  padding-bottom: 40rpx;
}

.status-card {
  display: flex;
  align-items: center;
  background: #fff;
  margin: 20rpx;
  padding: 40rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  .status-icon {
    width: 80rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 24rpx;
    
    .icon-text {
      font-size: 40rpx;
    }
  }
  
  .status-info {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .status-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .status-desc {
    font-size: 24rpx;
    color: #999;
  }
}

.section {
  background: #fff;
  margin: 20rpx;
  padding: 32rpx;
  border-radius: 16rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
  }
}

.info-item {
  display: flex;
  align-items: flex-start;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .info-label {
    width: 160rpx;
    font-size: 28rpx;
    color: #999;
    flex-shrink: 0;
  }
  
  .info-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    text-align: right;
    word-break: break-all;
  }
}

.merchant-info {
  .merchant-name {
    font-size: 28rpx;
    color: #333;
  }
}

.goods-list {
  .goods-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .goods-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
  }
  
  .goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .goods-name {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .goods-spec {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 12rpx;
  }
  
  .goods-price-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .goods-price {
    font-size: 26rpx;
    color: #ff4757;
  }
  
  .goods-quantity {
    font-size: 24rpx;
    color: #999;
  }
  
  .goods-subtotal {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-left: 20rpx;
  }
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  
  &.total {
    padding-top: 24rpx;
    border-top: 1rpx solid #f5f5f5;
    margin-top: 8rpx;
  }
  
  .price-label {
    font-size: 28rpx;
    color: #666;
  }
  
  .price-value {
    font-size: 28rpx;
    color: #333;
    
    &.highlight {
      font-size: 34rpx;
      font-weight: 600;
      color: #ff4757;
    }
  }
}

.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  gap: 20rpx;
  background: #fff;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
  
  .action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;
    
    &.primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
    }
    
    &.outline {
      background: #fff;
      border: 2rpx solid #ddd;
      color: #666;
    }
    
    &.danger {
      background: #fff;
      border: 2rpx solid #ff4757;
      color: #ff4757;
    }
  }
}
</style>

